package api

import (
	"encoding/json"
	"errors"
	"fmt"
)

// MapFilter2Json 过滤返回字段，并格式化输出json
func MapFilter2Json(fields []string, fieldMap map[string]interface{}) ([]byte, error) {
	if len(fields) == 0 {
		return map2Json(fieldMap)
	}
	outputMap := make(map[string]interface{})
	for _, fd := range fields {
		if v, ok := fieldMap[fd]; ok {
			outputMap[fd] = v
		} else {
			return nil, errors.New("请求字段不存在")
		}
	}
	return map2Json(outputMap)
}

func map2Json(fieldMap map[string]interface{}) ([]byte, error) {
	//	b, err := json.Marshal(fieldMap)
	b, err := json.MarshalIndent(fieldMap, "", "")

	return b, err
}

// Response2Json api 返回json格式
func Response2Json(code int, data []byte, message string, err error) []byte {
	resp := make([]byte, 0, len(data)+128)
	resp = append(resp, '{')
	// resp = append(resp, "\r\n"...)
	cd := fmt.Sprintf("\"status\":%d", code)
	resp = append(resp, cd...)
	msg := fmt.Sprintf(",\"message\":\"%s\"", message)
	resp = append(resp, msg...)

	if data != nil {
		resp = append(resp, ",\"data\":"...)
		resp = append(resp, data...)
	}

	if err != nil {
		er := fmt.Sprintf(",\"more info\":\"%s\"", err.Error())
		resp = append(resp, er...)
	}
	resp = append(resp, '}')
	fmt.Printf("------resp:%s\n", string(resp))
	return resp
}

type respData struct {
	Status  int         `json:"status"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
	More    string      `json:"more info"`
}

// 响应结果转json
// code 状态码
// data 结果数据, 如果data是json编码过，最终结果data会json编码两次
// message 提示信息
// err 更多的提示信息
func Response2JsonObj(code int, data interface{}, message string, err error) []byte {
	resp := respData{}
	resp.Status = code
	if data != nil {
		resp.Data = data
	}
	resp.Message = message
	if err != nil {
		resp.More = err.Error()
	}

	d, errj := json.Marshal(resp)
	if errj != nil {
		return []byte("{}")
	}
	fmt.Printf("------resp:%s\n", string(d))

	return d
}
